import os

import numpy as np
from PIL import Image
from paddleocr import PaddleOCR

from base.ocr_base_tool import crop_and_save_image, move_file, keep_from_guang


def get_rotate_angle(recognized_text_list_of_one_page):
    rotate = 0
    if len(recognized_text_list_of_one_page) > 0:
        if recognized_text_list_of_one_page is None or recognized_text_list_of_one_page[0] is None:
            return rotate
    boxes = [line[0] for line in recognized_text_list_of_one_page[0]]
    img_crop_width = 0
    img_crop_height = 0

    for points in boxes:
        # 求范数，得到宽度
        img_crop_width += np.linalg.norm(np.array(points[0]) - np.array(points[1]))
        # # 求范数，得到高度
        img_crop_height += np.linalg.norm(np.array(points[1]) - np.array(points[2]))
    if img_crop_width < img_crop_height:
        rotate = 90

    return rotate


class HousePlan:
    def __init__(self, output_path="", image_path="", address=""):
        self._address = address
        self._image_path = image_path
        self._output_path = output_path

        self._whole_strings_in_one_page = ""
        self._info_list_in_one_page = None
        self._paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch", max_text_length=64)

    @property
    def address(self):
        return self._address

    @address.setter
    def address(self, value):
        self._address = value

    @property
    def image_path(self):
        return self._image_path

    @image_path.setter
    def image_path(self, value):
        self._image_path = value

    def recognize(self, image_path):
        self.image_path = image_path
        # self.recognize_house_plan_on_fixed_location(image_path)
        self.recognize_house_plan_on_most_likely_location(image_path)
        self._address = keep_from_guang(self._address)

    def recognize_address_from_whole_page_by_pdf(self,pdf_file_path):

    def recognize_address_from_whole_page(self, image_path):
        # 使用paddleocr识别图像中的文本
        result = self._paddle_ocr.ocr(image_path, det=True, rec=True)

        ocr_result_pages_unit = result
        recognized_line_list_in_one_page = ocr_result_pages_unit[0]
        for index, text_list in enumerate(recognized_line_list_in_one_page):
            text = text_list[1][0]
            if '州市南沙区' in text:
                self._address = text

        if self._address.strip() != "":
            # 处理结束后将已经处理成功的输入文件转移至指定目录
            destination_dir_path = self._output_path + r'/finished_house_plan'
            self._image_path = os.path.join(destination_dir_path, os.path.basename(image_path))
            move_file(image_path, destination_dir_path)

            print(f'通过识别整页得到的 座落：{self._address}')
        else:
            # 处理结束后将已经处理成功的输入文件转移至指定目录
            print("通过整页扫描房屋分户图，识别座落失败！")
            move_file(image_path, self._output_path + r'/problem_house_plan')

    def recognize_house_plan_on_fixed_location(self, image_path):
        self._image_path = image_path
        # 先截取图片再识别
        # 一定要有一定的扩展，否则会识别不出来的
        coordinate_on_image = [368, 278, 865, 359]

        image_name_with_extension = os.path.basename(image_path)
        image_name_without_extension, extension = os.path.splitext(image_name_with_extension)

        cropped_image_path = os.path.dirname(image_path) + f"/{image_name_without_extension}_cropped{extension}"

        # 截取指定位置
        crop_and_save_image(image_path, coordinate_on_image, cropped_image_path)

        # 使用PaddleOCR识别图片中的文字
        result = self._paddle_ocr.ocr(cropped_image_path, cls=True)

        if result and len(result) > 0 and result[0]:
            for recognized_content_list in result[0]:
                self._address = self._address + recognized_content_list[1][0]
            if '州' in self._address:
                if '南沙' in self._address:
                    # 处理结束后将已经处理成功的输入文件转移至指定目录
                    destination_dir_path = self._output_path + r'/finished_house_plan'
                    self._image_path = os.path.join(destination_dir_path, os.path.basename(image_path))
                    move_file(image_path, destination_dir_path)
                    move_file(cropped_image_path, destination_dir_path)
                    print(f"{image_path}在固定位置上识别出的座落：{self._address}")
                    return

        move_file(cropped_image_path, self._output_path + r'/problem_house_plan')

        print(f"{image_path}的坐落第一次识别结果为空！可能需要旋转图片")

        image = Image.open(image_path)

        if image:

            rotated_img = image.rotate(270, expand=True)

            # 创建一个新的图像，背景颜色为白色
            new_img = Image.new("RGB", rotated_img.size, "white")

            # 将旋转后的图像粘贴到新图像上
            new_img.paste(rotated_img, (0, 0))

            rotated_image_path = os.path.dirname(image_path) + f"/{image_name_without_extension}_rotated{extension}"
            new_img.save(rotated_image_path)

            cropped_image_path = os.path.dirname(
                image_path) + f"/{image_name_without_extension}_cropped_rotated{extension}"

            cropped_img = Image.open(rotated_image_path).crop((487, 265, 1164, 363))
            # 保存截取后的图片
            cropped_img.save(cropped_image_path)

            result = self._paddle_ocr.ocr(cropped_image_path, cls=True)

            if result and len(result) > 0 and result[0]:

                for recognized_content_list in result[0]:
                    self._address = self._address + recognized_content_list[1][0]

                if '州' in self._address:
                    if '南沙区' in self._address:
                        # 处理结束后将已经处理成功的输入文件转移至指定目录
                        destination_dir_path = self._output_path + r'/finished_house_plan'
                        self._image_path = os.path.join(destination_dir_path, os.path.basename(image_path))
                        move_file(image_path, destination_dir_path)
                        move_file(cropped_image_path, destination_dir_path)

                        print(f"{image_path}在固定位置上识别出的座落：{self._address}")

                        return

            print(f"{image_path}的坐落在图片旋转90度后第二次识别结果为空！改为整页识别：")

            # 整页识别#######################################################################################

            self.recognize_address_from_whole_page(image_path)

            move_file(cropped_image_path, self._output_path + r'/problem_house_plan')

    # 可能用不上了，改用PDF识别
    # def recognize_house_plan_on_most_likely_location(self, image_path):
    #     self._image_path = image_path
    #
    #     # 先截取图片再识别
    #     # 一定要有一定的扩展，把最有可能的区域计算出来
    #     image = Image.open(image_path)
    #     left_ratio = 800 / 1743
    #     right_ratio = 1600 / 1743
    #     top_ratio = 50 / 2330
    #     bottom_ratio = 350 / 2330
    #
    #     left = (int)(left_ratio * image.width)
    #     right = (int)(right_ratio * image.width)
    #     top = (int)(top_ratio * image.height)
    #     bottom = (int)(bottom_ratio * image.height)
    #     image.close()
    #
    #     coordinate_on_image = [left, top, right, bottom]  # 图片大小为：1743 * 2330
    #
    #     cropped_image_path = os.path.dirname(image_path) + f"/{image_name_without_extension}_cropped{extension}"
    #
    #     # 截取指定位置
    #     crop_and_save_image(image_path, coordinate_on_image, cropped_image_path)
    #
    #     # 使用PaddleOCR识别图片中的文字
    #     result = self._paddle_ocr.ocr(cropped_image_path, cls=True)
    #
    #     if result and len(result) > 0 and result[0]:
    #         for recognized_content_list in result[0]:
    #             self._address = self._address + recognized_content_list[1][0]
    #         if '州' in self._address:
    #             # 处理结束后将已经处理成功的输入文件转移至指定目录
    #             destination_dir_path = self._output_path + r'/finished_house_plan'
    #             self._image_path = os.path.join(destination_dir_path, os.path.basename(image_path))
    #             move_file(image_path, destination_dir_path)
    #             move_file(cropped_image_path, destination_dir_path)
    #             print(f"{image_path}在固定位置上识别出的座落：{self._address}")
    #             return
    #
    #     move_file(cropped_image_path, self._output_path + r'/problem_house_plan')
    #
    #     print(f"{image_path}的坐落第一次识别结果为空！可能需要旋转图片")
    #
    #     image = Image.open(image_path)
    #
    #     if image:
    #
    #         rotated_img = image.rotate(270, expand=True)
    #
    #         # 创建一个新的图像，背景颜色为白色
    #         new_img = Image.new("RGB", rotated_img.size, "white")
    #
    #         # 将旋转后的图像粘贴到新图像上
    #         new_img.paste(rotated_img, (0, 0))
    #
    #         rotated_image_path = os.path.dirname(image_path) + f"/{image_name_without_extension}_rotated{extension}"
    #         new_img.save(rotated_image_path)
    #
    #         cropped_image_path = os.path.dirname(
    #             image_path) + f"/{image_name_without_extension}_cropped_rotated{extension}"
    #
    #         cropped_img = Image.open(rotated_image_path).crop((487, 265, 1164, 363))
    #         # 保存截取后的图片
    #         cropped_img.save(cropped_image_path)
    #
    #         result = self._paddle_ocr.ocr(cropped_image_path, cls=True)
    #
    #         if result and len(result) > 0 and result[0]:
    #
    #             for recognized_content_list in result[0]:
    #                 self._address = self._address + recognized_content_list[1][0]
    #
    #             if '州' in self._address:
    #                 if '南沙区' in self._address:
    #                     # 处理结束后将已经处理成功的输入文件转移至指定目录
    #                     destination_dir_path = self._output_path + r'/finished_house_plan'
    #                     self._image_path = os.path.join(destination_dir_path, os.path.basename(image_path))
    #                     move_file(image_path, destination_dir_path)
    #                     move_file(cropped_image_path, destination_dir_path)
    #
    #                     print(f"{image_path}在固定位置上识别出的座落：{self._address}")
    #
    #                     return
    #
    #         print(f"{image_path}的坐落在图片旋转90度后第二次识别结果为空！改为整页识别：")
    #
    #         # 整页识别#######################################################################################
    #
    #         self.recognize_address_from_whole_page(image_path)
    #
    #         move_file(cropped_image_path, self._output_path + r'/problem_house_plan')
